package org.agridata.akvisualization.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.agridata.akvisualization.doMain.entity.PriceTrend;
import org.agridata.akvisualization.doMain.vo.PriceTrendVo;
import org.agridata.akvisualization.mapper.PriceTrendMapper;
import org.agridata.akvisualization.result.Result;
import org.agridata.akvisualization.service.PriceTrendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: yxc
 * @date: 2024/2/21 16:38
 * @Description: 价格走势
 */
@Service
public class PriceTrendServiceImpl implements PriceTrendService {

    @Autowired
    PriceTrendMapper priceTrendMapper;

    @Override
    public Result importPriceTrend(List<PriceTrend> memberList, String dates, String monthly) {
        int successCount = 0;
        int failureCount = 0;
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将LocalDateTime格式化为字符串
        String formattedTime = currentTime.format(formatter);
        //截取日期后面的数字
        // 查找"-"字符的位置
        int dashIndex = dates.indexOf('-');

        // 截取"-"后面的部分
        String afterDash = dates.substring(dashIndex + 1);

        List<Map<String,Object>> SaveCrop = priceTrendMapper.selectPriceTrendByDates(dates, monthly);
        if (SaveCrop.size() > 0) {
            priceTrendMapper.deletePriceTrend(SaveCrop);
        }

        for (PriceTrend animalSaveCrop : memberList) {
            try {
                animalSaveCrop.setDate(dates);
                animalSaveCrop.setCreateAt(formattedTime);
                animalSaveCrop.setWeek(monthly);
                animalSaveCrop.setMonthly(afterDash);
                priceTrendMapper.insertPriceTrend(animalSaveCrop);
                successCount++;
            } catch (Exception e) {
                failureCount++;
                e.printStackTrace();
            }
        }
        return Result.ok("成功："+ successCount+ "条"+"，"+"失败"+failureCount+"条");
    }

    @Override
    public Page<PriceTrendVo> getPriceTrendList(String data, String monthly, Long pageNum, Long pageSize) {
        Page<PriceTrendVo> page = new Page<>(pageNum,pageSize);
        Page<PriceTrendVo> animalList = priceTrendMapper.getPriceTrendList(page, data, monthly);
        return animalList;
    }

    @Override
    public Result pricePerMensems() {
        List<Map<String, Object>> maps = priceTrendMapper.pricePerMensems();
        return Result.ok(maps);
    }

}
